package com.jay.codec.utils

/**
 * @author xuzhou4
 * @date 2022/1/7
 */
object ByteUtils {

    fun toInt(byteArray: ByteArray): Int {
        return byteArray[0].toUInt().toInt()
            .shl(24) or byteArray[1].toUInt().toInt()
            .shl(16) or byteArray[2].toUInt().toInt()
            .shl(8) or byteArray[3].toUInt().toInt()
    }

    @JvmStatic
    fun merge(bytes: ByteArray, bytes1: ByteArray): ByteArray {
        val byteArray = ByteArray(bytes.size + bytes1.size)
        System.arraycopy(bytes, 0, byteArray, 0, bytes.size)
        System.arraycopy(bytes1, 0, byteArray, bytes.size, bytes1.size)
        return byteArray
    }

    @JvmStatic
    fun toBytes(source: String): ByteArray {
        return source.toByteArray()
    }

    @JvmStatic
    fun toBytes(num: Int): ByteArray {
        val byteArray = ByteArray(4)
        byteArray[0] = ((num shr 24) and 0xFF).toByte()
        byteArray[1] = ((num shr 16) and 0xFF).toByte()
        byteArray[2] = ((num shr 8) and 0xFF).toByte()
        byteArray[3] = (num and 0xFF).toByte()
        return byteArray
    }


    @JvmStatic
    fun toBytesLittle(num: Int): ByteArray {
        val byteArray = ByteArray(4)
        byteArray[3] = ((num shr 24) and 0xFF).toByte()
        byteArray[2] = ((num shr 16) and 0xFF).toByte()
        byteArray[1] = ((num shr 8) and 0xFF).toByte()
        byteArray[0] = (num and 0xFF).toByte()
        return byteArray
    }

    @JvmStatic
    fun toBytesLittle(num: Short): ByteArray {
        val byteArray = ByteArray(2)
        byteArray[1] = ((num.toInt() shr 8) and 0xFF).toByte()
        byteArray[0] = (num.toInt() and 0xFF).toByte()
        return byteArray
    }
}